#!/usr/bin/env python
#encoding=utf8
"""
@描述：打印出行业二级标签的json格式
       用两种方法，1.直接方式，2.类结构方式
@日期：2015年01月28日 星期三
@作者：hongxingfan
"""

import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding("utf8")

def openConn():
	conn = MySQLdb.connect(host="192.168.1.251",user="root",passwd="",db="jobs",charset="utf8")
	return conn

if __name__ == "__main__":
	conn = openConn()
	select = "SELECT firstName,firstId,secondName,secondId FROM industry_tag ORDER BY firstId ASC,secondId ASC"
	cur = conn.cursor()
	cur.execute(select)
	result = cur.fetchall()

	key = None
	# 采用list结构加以完善
	jsonContent = []
	jsonContent.append("\"industry_1\":[")
	#print("\"industry_1\":[")
	for (firstName,firstId,secondName,secondId) in result:
		if(firstName != key):
			if(key is not None):
				jsonContent.pop()
				jsonContent.append("]},{\"code\":%d," %(firstId))
				#print("]},{\"code\":%d," %(firstId))
			else:
				jsonContent.append("{\"code\":%d," %(firstId))
				#print("{\"code\":%d," %(firstId))
			jsonContent.append("\"name\":\"%s\"," %(firstName))
			#print("\"name\":\"%s\"," %(firstName))
			jsonContent.append("\"child\":[")
			#print("\"child\":[")
			jsonContent.append("{\"code\":%d," %(secondId))
			#print("{\"code\":%d," %(secondId))
			jsonContent.append("\"name\":\"%s\"" %(secondName))
			#print("\"name\":\"%s\"" %(secondName))
			jsonContent.append("}")
			jsonContent.append(",")
			#print("},")
		else:
			jsonContent.append("{\"code\":%d," %(secondId))
			#print("{\"code\":%d," %(secondId))
			jsonContent.append("\"name\":\"%s\"" %(secondName))
			#print("\"name\":\"%s\"" %(secondName))
			jsonContent.append("}")
			jsonContent.append(",")
			#print("},"), # 这里有个问题，最后一个需要手动替换
		key = firstName
	# 删除最后一个","
	jsonContent.pop()
	jsonContent.append("]}]")
	#print("]}]")
	for item in jsonContent:
		print(item)
	conn.close()
